﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using ShootSearch.Util;
using ShootSearch.Util.Serializers;
using ShootSearch.Runner.Controls;
using ShootSearch.Runner.Configurations;
using Quartz;
using ShootSearch.Core;
using System.Diagnostics;
using System.IO;

namespace ShootSearch.Runner
{
    public partial class FormNewTask : Form
    {
        private NewTaskConfig config = null;
        private TaskConfig taskConfig = new TaskConfig();
        private FormConfiguration configForm = new FormConfiguration();
        private string taskPath = RunnerHelper.TaskPath;
        

        public FormNewTask()
        {
            InitializeComponent();
            config = NewTaskConfig.Load();
            comboBoxLaunchType.Items.Clear();
            comboBoxLaunchType.DataSource = Enum.GetNames(typeof(LaunchType));
            comboBoxLaunchType.SelectedIndex = 0;
        }

        #region Public Methods
        public TaskConfig GetTaskConfig()
        {
            return taskConfig;
        }

        public string GetContextPath()
        {
            return textBoxPath.Text;
        }

        public void LoadTaskConfig(TaskConfig tc)
        {
            buttonChange.Enabled = false;
            textBoxName.Enabled = false;
            taskPath = new DirectoryInfo(tc.ContextPath).Parent.FullName;
            comboBoxLaunchType.SelectedIndex = comboBoxLaunchType.Items.IndexOf( tc.LaunchType.ToString());
            ImportTask(tc);

        }

        public void ImportTask(TaskConfig tc)
        {
            textBoxName.Text = tc.TaskName;
            taskConfig = tc;
            for (int i = 0; i < tc.Jobs.Count; i++)
            {
                AddJob(tc.Jobs[i]);
            }
        }
        
        #endregion

        #region Private Methods
        private void AddJob(JobConfig job)
        {
            string[] att = new string[]
            {
                job.Type.TypeName, 
                job.Type.Assembly
            };

            if (string.IsNullOrEmpty(job.Name))
            {
                job.Name = job.Type.TypeName;
            }
            else att[0] = job.Name;

            ListViewItem item = new ListViewItem(att);
            item.ImageIndex = job.IconIndex;
            item.Tag = job;
            listViewTask.Items.Add(item);

        }

        private void ShowTaskNamePath()
        {
            if (textBoxName.Text.Length > 0)
            {
                string name = Util.IO.FormatFilename(textBoxName.Text);
                textBoxPath.Text = IO.FormatDirName(taskPath + "\\" + name, false);
            }
        }
        
        #endregion
        
        #region Form Events
        private void NewTask_Load(object sender, EventArgs e)
        {
            listViewJobs.Items.Clear();
            listViewJobs.Groups.Clear();
            foreach (string item in config.Groups)
            {
                listViewJobs.Groups.Add(new ListViewGroup(item));
            }

            foreach (JobEntity jobEntity in config.Jobs)
            {
                ListViewItem item = new ListViewItem(new string[] 
                { 
                    jobEntity.Assembly.TypeName, jobEntity.Assembly.Assembly 
                });
                item.Tag = jobEntity.Assembly;
                item.ImageIndex = jobEntity.Group;
                item.Group = listViewJobs.Groups[jobEntity.Group];
                listViewJobs.Items.Add(item);
            }

          
        } 
        #endregion
        
        #region Button Events
        private void buttonChange_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            if (!string.IsNullOrEmpty(textBoxPath.Text))
            {
                fbd.SelectedPath = textBoxPath.Text;
            }
            else
            {
                fbd.SelectedPath = taskPath;
            }
            //sfd.Filter = "Xml File|*.xml";
            if (fbd.ShowDialog() == DialogResult.OK)
            {
                taskPath = IO.FormatDirName(fbd.SelectedPath);

                ShowTaskNamePath();

            }
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            if (listViewJobs.SelectedItems.Count == 0) return;

            AssemblyConfig assembly = listViewJobs.SelectedItems[0].Tag as AssemblyConfig;
            if (assembly != null)
            {
                try
                {
                    ISpiderMan job = assembly.GetObject() as ISpiderMan;
                    if (job != null)
                    {
                        SpiderManConfig detail = job.Config;
                        JobConfig jobConfig = new JobConfig();
                        jobConfig.Name = job.GetType().FullName;
                        jobConfig.Type = new AssemblyConfig(job.GetType());
                        jobConfig.Config = detail;
                        jobConfig.IconIndex = listViewJobs.SelectedItems[0].ImageIndex;
                        //jobConfig.Type = new AssemblyConfig(job.GetType());
                        AddJob(jobConfig);


                        //jobIndex++;
                    }

                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }

        }

        private void buttonRemove_Click(object sender, EventArgs e)
        {
            if (listViewTask.SelectedItems.Count == 0) return;
            listViewTask.Items.RemoveAt(listViewTask.SelectedItems[0].Index);

        }

        private void buttonEdit_Click(object sender, EventArgs e)
        {
            if (listViewTask.SelectedItems.Count == 0) return;
            //JobDetail detail = listViewTask.SelectedItems[0].Tag as JobDetail;
            //object jobConfig = detail.JobDataMap[Task.JOB_CONFIG];
            AssemblyWithConfig jobConfig = listViewTask.SelectedItems[0].Tag as AssemblyWithConfig;
            configForm.Config = jobConfig.Config;

            if (configForm.ShowDialog() == DialogResult.OK)
            {
                jobConfig.Config = configForm.Config as SpiderManConfig;
                listViewTask.SelectedItems[0].Tag = jobConfig;
            }


        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            if (textBoxName.Text.Length == 0 ||
                (textBoxName.Enabled && File.Exists(IO.FormatDirName(textBoxPath.Text) + Task.TAKS_CONFIG)))
            {
                MessageBox.Show("Name empty or the task was already exist!");
                return;
            }

            if (listViewTask.Items.Count == 0)
            {
                this.DialogResult = DialogResult.Cancel;
            }
            else
            {
                textBoxPath.Text = IO.FormatDirName(taskPath + "\\" + textBoxName.Text, true);
                taskConfig.TaskName = textBoxName.Text;
                taskConfig.Jobs.Clear();
                foreach (ListViewItem item in listViewTask.Items)
                {
                    JobConfig jobConfig = item.Tag as JobConfig;
                    taskConfig.Jobs.Add(jobConfig);
                }
                taskConfig.ContextPath = IO.FormatDirName(textBoxPath.Text);
                taskConfig.LaunchType = (LaunchType)Enum.Parse(
                    typeof(LaunchType),
                    comboBoxLaunchType.SelectedItem.ToString());

                this.DialogResult = DialogResult.OK;

            }


        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        } 
        #endregion

        #region Other Controls' Events
        private void textBoxName_TextChanged(object sender, EventArgs e)
        {
            ShowTaskNamePath();
        }

        private void listViewJobs_DoubleClick(object sender, EventArgs e)
        {
            buttonAdd_Click(sender, e);
        }

        private void listViewTask_DoubleClick(object sender, EventArgs e)
        {
            buttonEdit_Click(sender, e);
        }

        private void listViewTask_AfterLabelEdit(object sender, LabelEditEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.Label))
            {
                JobConfig jobConfig = listViewTask.Items[e.Item].Tag as JobConfig;
                jobConfig.Name = e.Label;
            }
        }
        #endregion


     
    }
}
